package com.iwomy.secureplat.platform.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iwomy.secureplat.common.core.util.R;
import com.iwomy.secureplat.common.excel.annotation.ResponseExcel;
import com.iwomy.secureplat.common.log.annotation.SysLog;
import com.iwomy.secureplat.common.security.util.SecurityUtils;
import com.iwomy.secureplat.platform.dto.BasicDeviceModelDTO;
import com.iwomy.secureplat.platform.entity.BasicAuthorizationRecordEntity;
import com.iwomy.secureplat.platform.entity.BasicDeviceModelEntity;
import com.iwomy.secureplat.platform.exception.PlatformException;
import com.iwomy.secureplat.platform.service.BasicAuthorizationRecordService;
import com.iwomy.secureplat.platform.service.BasicDeviceModelService;
import com.wf.captcha.GifCaptcha;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 设备型号表
 *
 * @author pig
 * @date 2023-11-14 14:43:58
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/basicDeviceStock" )
@Tag(description = "basicDeviceStock" , name = "设备型号表管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class BasicDeviceStockController {

    private final  BasicDeviceModelService basicDeviceModelService;

    private final BasicAuthorizationRecordService basicAuthorizationRecordService;

	private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 分页查询
     * @param page 分页对象
     * @param basicDeviceModelDTO 设备型号表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('platform_basicDeviceStock_view')" )
    public R getBasicDeviceStockPage(@ParameterObject Page page, @ParameterObject BasicDeviceModelDTO basicDeviceModelDTO) {
		return R.ok(basicDeviceModelService.getBasicDeviceStockPage(page, basicDeviceModelDTO));
    }


    /**
     * 通过id查询设备型号表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('platform_basicDeviceStock_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(basicDeviceModelService.getById(id));
    }

    /**
     * 新增设备型号表
     * @param basicDeviceModel 设备型号表
     * @return R
     */
    @Operation(summary = "新增设备型号表" , description = "新增设备型号表" )
    @SysLog("新增设备型号表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('platform_basicDeviceStock_add')" )
    public R save(@RequestBody BasicDeviceModelEntity basicDeviceModel) {
		BasicDeviceModelEntity wrapperEntity = new BasicDeviceModelEntity();
		wrapperEntity.setDeviceModelName(basicDeviceModel.getDeviceModelName());
		LambdaQueryWrapper<BasicDeviceModelEntity> wrapper = Wrappers.lambdaQuery(wrapperEntity);
		BasicDeviceModelEntity one = basicDeviceModelService.getOne(wrapper);
		if(ObjectUtil.isNotNull(one)){
			throw new PlatformException("设备型号已存在");
		}
		basicDeviceModel.setDeptId(SecurityUtils.getUser().getDeptId());
        return R.ok(basicDeviceModelService.save(basicDeviceModel));
    }

    /**
     * 修改设备型号表
     * @param basicDeviceModel 设备型号表
     * @return R
     */
    @Operation(summary = "修改设备型号表" , description = "修改设备型号表" )
    @SysLog("修改设备型号表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('platform_basicDeviceStock_edit')" )
    public R updateById(@RequestBody BasicDeviceModelEntity basicDeviceModel) {
		BasicDeviceModelEntity wrapperEntity = new BasicDeviceModelEntity();
		wrapperEntity.setDeviceModelName(basicDeviceModel.getDeviceModelName());
		LambdaQueryWrapper<BasicDeviceModelEntity> wrapper = Wrappers.lambdaQuery(wrapperEntity);
		BasicDeviceModelEntity one = basicDeviceModelService.getOne(wrapper);
		if(ObjectUtil.isNotNull(one)&&!one.getId().equals(basicDeviceModel.getId())){
			throw new PlatformException("设备型号已存在");
		}
        return R.ok(basicDeviceModelService.updateById(basicDeviceModel));
    }

	/**
	 * 启用禁用
	 * @param basicDeviceModel 设备型号
	 * @return R
	 */
	@Operation(summary = "启用禁用设备型号" , description = "启用禁用设备型号" )
	@SysLog(expression = "'启用禁用设备型号'.concat(#basicDeviceModel.remarks)" )
	@PutMapping("/enableOrDisable")
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceStock_enableOrDisable')" )
	public R enableOrDisable(@RequestBody BasicDeviceModelDTO basicDeviceModel) {

		BasicDeviceModelEntity basicDeviceModelEntity = new BasicDeviceModelEntity();
		basicDeviceModelEntity.setId(basicDeviceModel.getId());
		basicDeviceModelEntity.setRemarks(basicDeviceModel.getRemarks());
		basicDeviceModelEntity.setState(basicDeviceModel.getState());
		return R.ok(basicDeviceModelService.updateById(basicDeviceModelEntity));
	}

    /**
     * 通过id删除设备型号表
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除设备型号表" , description = "通过id删除设备型号表" )
    @SysLog("通过id删除设备型号表" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('platform_basicDeviceStock_del')" )
    public R removeById(@RequestBody Long[] ids) {
		return R.ok(basicDeviceModelService.removeBatchByIds(CollUtil.toList(ids)));
    }

	/**
	 * 产品库通过id删除设备型号表
	 * @param ids id列表
	 * @return R
	 */
	@Operation(summary = "通过id删除设备型号表" , description = "通过id删除设备型号表" )
	@SysLog("产品库通过id删除设备型号表" )
	@PutMapping("/deleteModel")
	public R deleteModel(@RequestBody Long[] ids) {
		List<Long> idList = CollUtil.toList(ids);
		//产品库删除型号时，设备型号状态改为禁用20
		LambdaQueryWrapper<BasicDeviceModelEntity> wrapper = Wrappers.<BasicDeviceModelEntity>lambdaQuery();
		wrapper.in(BasicDeviceModelEntity::getId, idList);
		List<BasicDeviceModelEntity> deviceModelList = basicDeviceModelService.list(wrapper);
		for (BasicDeviceModelEntity deviceModel : deviceModelList) {
			deviceModel.setState(20);
		}
		//产品库删除型号时，授权记录状态改为取消授权20，因为授权记录不删除
		LambdaQueryWrapper<BasicAuthorizationRecordEntity> authorizationWrapper = Wrappers.<BasicAuthorizationRecordEntity>lambdaQuery();
		authorizationWrapper.in(BasicAuthorizationRecordEntity::getId, idList);
		List<BasicAuthorizationRecordEntity> authorizationList = basicAuthorizationRecordService.list(authorizationWrapper);
		for (BasicAuthorizationRecordEntity authorization : authorizationList) {
			authorization.setState(20);
		}
		basicAuthorizationRecordService.updateBatchById(authorizationList);

		return R.ok(basicDeviceModelService.updateBatchById(deviceModelList));
	}



	/**
     * 导出excel 表格
     * @param basicDeviceModel 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('platform_basicDeviceStock_export')" )
    public List<BasicDeviceModelEntity> export(BasicDeviceModelEntity basicDeviceModel,Long[] ids) {
        return basicDeviceModelService.list(Wrappers.lambdaQuery(basicDeviceModel).in(ArrayUtil.isNotEmpty(ids), BasicDeviceModelEntity::getId, ids));
    }

	/**
	 * 分页查询
	 * @param basicDeviceModel 设备类型
	 * @return
	 */
	@Operation(summary = "分页查询" , description = "分页查询" )
	@GetMapping("/list" )
	@PreAuthorize("@pms.hasPermission('platform_basicDeviceStock_view')" )
	public R getBasicDeviceModelList( @ParameterObject BasicDeviceModelEntity basicDeviceModel) {
		LambdaQueryWrapper<BasicDeviceModelEntity> wrapper = Wrappers.lambdaQuery(basicDeviceModel);
		return R.ok(basicDeviceModelService.list( wrapper));
	}

	/**
	 * 验证码
	 *
	 * @return
	 */
	@GetMapping("/captcha")
	public R captcha() throws Exception {
		GifCaptcha captcha = new GifCaptcha(130, 48, 4);
		redisTemplate.opsForValue().set("captcha", captcha.text().toLowerCase(), 600, TimeUnit.SECONDS);
		String codeImg = captcha.toBase64();
		System.out.println("验证码是==================================" + captcha.text());
		Map<String, String> captchaMap = new HashMap<>();
		captchaMap.put("codeImg", codeImg);
		captchaMap.put("text", captcha.text());
		return R.ok(captchaMap);
	}

	/**
	 * 授权
	 *
	 * @param basicDeviceModelDTO 实体
	 */
	@SysLog("授权")
	@GetMapping("/authorize")
	public R authorize(@ParameterObject BasicDeviceModelDTO basicDeviceModelDTO) {
		String captchaValue = (String) redisTemplate.opsForValue().get("captcha");
		System.out.println("captchaValue================"+captchaValue);
		System.out.println("basicDeviceModelDTO.getCode().toLowerCase()=========="+basicDeviceModelDTO.getCode().toLowerCase());
		if (captchaValue != null && captchaValue.equals(basicDeviceModelDTO.getCode().toLowerCase())) {
			return basicDeviceModelService.authorize(basicDeviceModelDTO);
		} else {
			return R.failed("验证码校验不通过");
		}
	}
}